package com.sise.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.sise.common.dto.OrderDTO;
import com.sise.common.interfaces.OrderService;
import com.sise.dao.OrderDao;
import com.sise.model.OrderPO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author idea
 * @data 2019/10/7
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 模拟插入订单
     *
     * @param orderDTO
     * @return
     */
    @Override
    public Boolean createOrder(OrderDTO orderDTO) {
        OrderPO orderPO = new OrderPO();
        BeanUtils.copyProperties(orderDTO, orderPO);
        //模拟记录订单一小时后过期
        redisTemplate.opsForValue().set(orderDTO.getOrderNumber(),orderDTO);
        redisTemplate.expire(orderDTO.getOrderNumber(),15,TimeUnit.SECONDS);
        return orderDao.insert(orderPO) > 0;
    }

    /**
     * 更新订单 未支付订单 过期需要更新状态
     *
     * @param orderDTO
     * @return
     */
    @Override
    public Boolean updateExpireOrder(OrderDTO orderDTO) {
        OrderPO orderPO = new OrderPO();
        BeanUtils.copyProperties(orderDTO, orderPO);
        EntityWrapper<OrderPO> ew = new EntityWrapper<>();
        ew.eq("order_number", orderPO.getOrderNumber());
        ew.eq("pay_status",0);
        return orderDao.update(orderPO, ew) > 0;
    }
}
